package com.java.userservice.service;

import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.java.userservice.domain.User;
import com.java.userservice.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author cf
 * @date 2021/7/7 14:41
 */
@Service
public class UserService implements UserDetailsService {

    private List<User> userList;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) {
//        userList = new ArrayList<>();
//        userList.add(new User("macro", passwordEncoder.encode("123"), AuthorityUtils.commaSeparatedStringToAuthorityList("admin")));
//        userList.add(new User("andy", passwordEncoder.encode("123"), AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
//        userList.add(new User("mark", passwordEncoder.encode("123"), AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
//        List<User> findUserList = userList.stream().filter(user -> user.getUsername().equals(username)).collect(Collectors.toList());
//        if (!CollectionUtils.isEmpty(findUserList)) {
//            return findUserList.get(0);
//        } else {
//            throw new UsernameNotFoundException("用户名或密码错误");
//        }
        User user = new LambdaQueryChainWrapper<>(this.userMapper)
                .eq(User::getUsername, username).one();
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("账号密码不正确");
        }
        List<String> userPermissions = Arrays.asList("admin");
        String userPermissionString = StringUtils.join(userPermissions.toArray(), ",");
        return new org.springframework.security.core.userdetails.User(user.getUsername(), passwordEncoder.encode(user.getPassword()), AuthorityUtils.commaSeparatedStringToAuthorityList(userPermissionString));
//        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), true, true, true, true, user.getAuthorities());
    }
}
